package com.sdjz.club.club.utils;

import cn.hutool.json.JSONUtil;
import com.sdjz.club.club.common.lang.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ImageUtil {
    static String path = "E:\\";

    static public void updateImg(MultipartFile multipartFile, Long ID) throws IOException {
        byte[] bytes = multipartFile.getBytes();
        FileOutputStream fop = new FileOutputStream(path + ID);
        fop.write(bytes);
        fop.close();
    }

    static public void getImg(HttpServletResponse response, String ID) throws Exception {
        ServletOutputStream os = response.getOutputStream();

        try {
            BufferedImage image = ImageIO.read(new FileInputStream(path + ID));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (IOException e) {
            log.error("获取图片异常{}", e.getMessage());
            response.setContentType("application/json;charset=UTF-8");
            CommonResult commonResult = CommonResult.fail("获取图片异常,图片不存在");
            os.write(JSONUtil.toJsonStr(commonResult).getBytes(StandardCharsets.UTF_8));
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }
}
